package servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.EntityManagerAux;
import managers.EntityManagerAux.LoginResult;

/**
 * Servlet implementation class LoginAdmin
 */
public class LoginAdmin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAdmin() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.getRequestDispatcher("loginAdmin.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@EJB EntityManagerAux ema;
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String pass = request.getParameter("pass");
		
		LoginResult loginResult = ema.loginAdmin(id, pass);
		
		if(loginResult == LoginResult.SUCCESS){
			request.getSession().setAttribute("id", id);
			response.sendRedirect("alertAdmin.jsp");	//redirect to the welcome-site
		}else if(loginResult == LoginResult.NEEDS_VALIDATION){
			request.setAttribute("loginResult", LoginResult.NEEDS_VALIDATION);
			request.getRequestDispatcher("loginAdmin.jsp").forward(request, response);
			//response.sendRedirect("login");
		}else if(loginResult == LoginResult.FAILURE){
			request.setAttribute("loginResult", LoginResult.FAILURE);
			request.getRequestDispatcher("loginAdmin.jsp").forward(request, response);
		}
	}
}
